<script setup lang="tsx">
import { h, ref } from 'vue';
import { NButton, NImage, NPopconfirm, NTag } from 'naive-ui';
import { $t } from '@/locales';
import { useTable, useTableOperate } from '@/hooks/common/table';
import { deleteOAuth2Client, fetchGetOAuth2ClientList, getFetchOAuth2ClientUrl } from '@/service/api';
import { useAuth } from '@/hooks/business/auth';
import { useAppStore } from '@/store/modules/app';
import SvgIcon from '@/components/custom/svg-icon.vue';
import { DICT_TYPE, getDictObj } from '@/utils/dict';
import OAuth2ClientSearch from './modules/client-search.vue';
import OAuth2ClientOperateModal from './modules/client-operate-modal.vue';

const wrapperRef = ref<HTMLElement | null>(null);
const appStore = useAppStore();
const { hasAuth } = useAuth();

const {
  columns,
  columnChecks,
  data,
  loading,
  mobilePagination,
  getData,
  getDataByPage,
  searchParams,
  resetSearchParams
} = useTable({
  apiFn: fetchGetOAuth2ClientList,
  showTotal: true,
  apiParams: {
    current: 1,
    size: 10,
    status: null,
    clientName: null
  },
  columns: () => [
    {
      type: 'selection'
    },
    {
      key: 'clientId',
      title: $t('page.manage.oauth2.client.clientId'),
      align: 'center',
      width: 180
    },
    {
      key: 'clientName',
      title: $t('page.manage.oauth2.client.clientName'),
      align: 'center',
      width: 180
    },
    {
      key: 'clientLogo',
      title: $t('page.manage.oauth2.client.clientLogo'),
      align: 'center',
      width: 120,
      render: row => {
        return h(NImage, {
          src: row.clientLogo,
          width: 40,
          objectFit: 'scale-down',
          fallbackSrc: row.clientLogo
        });
      }
    },
    {
      key: 'status',
      title: $t('page.manage.oauth2.client.status'),
      align: 'center',
      width: 150,
      render: row => {
        if (row.status === null) {
          return null;
        }
        const dictObj = getDictObj(DICT_TYPE.COMMON_STATUS, row.status);

        return <NTag type={dictObj?.colorType}>{dictObj?.label}</NTag>;
      }
    },
    {
      key: 'accessTokenTimeToLive',
      title: $t('page.manage.oauth2.client.accessTokenTimeToLive'),
      align: 'center',
      width: 180
    },
    {
      key: 'refreshTokenTimeToLive',
      title: $t('page.manage.oauth2.client.refreshTokenTimeToLive'),
      align: 'center',
      width: 200
    },
    {
      key: 'authorizationGrantTypes',
      title: $t('page.manage.oauth2.client.authorizationGrantTypes'),
      align: 'center',
      width: 450,
      render: row => {
        const authorizedGrantType = row.authorizationGrantTypes;
        return h(
          'div',
          authorizedGrantType.map(item => {
            const dictObj = getDictObj(DICT_TYPE.SYSTEM_OAUTH2_GRANT_TYPE, item);
            return h(
              NTag,
              {
                type: dictObj?.colorType,
                style: 'margin-right: 4px'
              },
              {
                default: () => item
              }
            );
          })
        );
      }
    },
    {
      key: 'clientIdIssuedAt',
      title: $t('page.manage.oauth2.client.clientIdIssuedAt'),
      align: 'center',
      width: 180
    },
    {
      key: 'operate',
      title: $t('common.operate'),
      align: 'center',
      fixed: 'right',
      width: 180,
      render: row => (
        <div class="flex-center gap-8px">
          <div v-show={hasAuth('system:oauth2-client:update')}>
            <NButton type="primary" ghost size="small" onClick={() => edit(row.id)}>
              {{
                default: () => $t('common.edit'),
                icon: () => h(SvgIcon, { icon: 'ep:edit' })
              }}
            </NButton>
          </div>
          <div v-show={hasAuth('system:oauth2-client:delete')}>
            <NPopconfirm onPositiveClick={() => handleDelete(row.id)}>
              {{
                default: () => $t('common.confirmDelete'),
                trigger: () => (
                  <NButton type="error" ghost size="small">
                    {{
                      default: () => $t('common.delete'),
                      icon: () => h(SvgIcon, { icon: 'ep:delete' })
                    }}
                  </NButton>
                )
              }}
            </NPopconfirm>
          </div>
        </div>
      )
    }
  ]
});

const {
  modelVisible,
  operateType,
  editingData,
  handleEdit,
  handleAdd,
  onDeleted,
  onBatchDeleted,
  checkedRowKeys,
  fetchDataUrl
  // closeDrawer
} = useTableOperate(data, getData);

async function handleDelete(id: number) {
  // request
  const { error } = await deleteOAuth2Client(id.toString());
  await onDeleted(error);
}
async function handleBatchDelete() {
  // request
  const { error } = await deleteOAuth2Client(checkedRowKeys.value.join(','));

  await onBatchDeleted(error);
}
function edit(id: number) {
  fetchDataUrl.value = getFetchOAuth2ClientUrl(id);
  handleEdit(id);
}
</script>

<template>
  <div ref="wrapperRef" class="flex-col-stretch gap-16px overflow-hidden lt-sm:overflow-auto">
    <OAuth2ClientSearch
      v-if="hasAuth('system:oauth2-client:query')"
      v-model:model="searchParams"
      @reset="resetSearchParams"
      @search="getDataByPage"
    />
    <NCard
      :title="$t('page.manage.oauth2.client.title')"
      :bordered="false"
      size="small"
      class="sm:flex-1-hidden card-wrapper"
    >
      <template #header-extra>
        <TableHeaderOperation
          v-model:columns="columnChecks"
          :disabled-delete="checkedRowKeys.length === 0"
          :loading="loading"
          create-auth="system:oauth2-client:create"
          delete-auth="system:oauth2-client:delete"
          @add="handleAdd"
          @delete="handleBatchDelete"
          @refresh="getData"
        />
      </template>
      <NDataTable
        v-model:checked-row-keys="checkedRowKeys"
        :columns="columns"
        :data="data"
        size="small"
        :flex-height="!appStore.isMobile"
        :scroll-x="2088"
        :loading="loading"
        :row-key="row => row.id"
        remote
        :pagination="mobilePagination"
        class="sm:h-full"
      />

      <OAuth2ClientOperateModal
        v-model:visible="modelVisible"
        :operate-type="operateType"
        :row-data="editingData"
        @submitted="getDataByPage"
      />
    </NCard>
  </div>
</template>

<style scoped></style>
